// Package controller @author dingrui @since 2021/11/27
package controller

import (
	"log"

	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/hero"

	"github.com/bannirui/mini-prize/common"
	"github.com/bannirui/mini-prize/dal/model"
	"github.com/bannirui/mini-prize/dal/service"
	"github.com/bannirui/mini-prize/web/entity/vo"
	"github.com/bannirui/mini-prize/web/util/response"
)

func AdminBlackIpRouter(party iris.Party) {
	var (
		party_     = party.Party("/admin-blackip")
		controller = AdminBlackIpController{}
	)
	party_.Get("/", hero.Handler(controller.Get))
	party_.Get("/black", hero.Handler(controller.GetBlack))
}

type AdminBlackIpController struct {
}

//
//  Get
//  @Description: 黑名单列表
//                GET http://localhost:8080/api/mini-prize/admin-blackip/?page=1&size=10
//                GET http://localhost:8080/api/mini-prize/admin-blackip/?page=1
//                GET http://localhost:8080/api/mini-prize/admin-blackip/?size=10
//                GET http://localhost:8080/api/mini-prize/admin-blackip/
//  @receiver c
//
func (c *AdminBlackIpController) Get(ctx iris.Context) {
	var (
		page     int
		size     int
		dataList []model.BlackIp
		prevPage int = -1 // -1表示没有前一页
		nextPage int = -1 // -1表示没有下一页
		total    int
	)
	page = ctx.URLParamIntDefault("page", 1)
	size = ctx.URLParamIntDefault("size", 50)
	// 数据列表
	dataList = service.G_blackIpService.GetAll(page, size)
	total = (page - 1) + len(dataList)
	// 数据总数
	if len(dataList) >= size {
		total = int(service.G_blackIpService.CountAll())
		nextPage = page + 1
	}
	if page > 1 {
		prevPage = page - 1
	}
	// 构造响应体
	response.Ok(ctx, response.CODE_OK, &vo.PageBlackIpVO{
		DataList: dataList,
		Total:    total,
		PrevPage: prevPage,
		NextPage: nextPage,
	})
	return
}

//
//  GetBlack
//  @Description: 根据id封禁ip
//                http://localhost:8080/api/mini-prize/admin-blackip/black?id=1&bannedDays=0
//  @receiver c
//
func (c *AdminBlackIpController) GetBlack(ctx iris.Context) {
	var (
		id         int
		err        error
		bannedDays int // 封禁时长(单位:天)
		expireTime int // 封禁截至(单位:秒)
	)
	if id, err = ctx.URLParamInt("id"); err != nil {
		// 入参异常
		response.Error(ctx, iris.StatusBadRequest, response.CODE_FAILUR)
		return
	}
	bannedDays = ctx.URLParamIntDefault("bannedDays", 0)
	if bannedDays > 0 {
		// XXX: 2021/11/27 expire是int类型 会因为入参的不合理导致溢出
		expireTime = bannedDays*86400 + common.NowUnix()
	}
	if err = service.G_blackIpService.Update(&model.BlackIp{Id: id, ExpireTime: expireTime, GmtUpdated: common.NowUnix()}, []string{"expire_time"}); err != nil {
		goto ERR
	}
	response.Ok(ctx, response.CODE_OK, nil)
	return
ERR:
	log.Println("[-] ERROR: ", err)
	response.InternalServerError(ctx, response.CODE_FAILUR)
	return
}
